/*
 * Copyright (c) 2008-20018 Saša Stamenković <umpirsky@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice,
 *    	this list of conditions and the following disclaimer in the documentation
 *    	and/or other materials provided with the distribution.
 *    * Neither the name of the <ORGANIZATION> nor the names of its contributors
 *    	may be used to endorse or promote products derived from this software without
 *    	specific prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 *    OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Register events on load.
 */
window.onload = function() {
	if (!umpirsky.isJavaEnabled()) {
		alert("You need to enable java!");
	}
	umpirsky.addEventListener("onLoad", initialize);
	umpirsky.addEventListener("fileListUpdated", updateFileList);
	umpirsky.addEventListener("uploadFinished", filesUploaded);
	umpirsky.addEventListener("onError", errorHandler);
	umpirsky.addEventListener("uploadProgressListener", uploadProgressListener);
}

/**
 * Error handler
 */
function errorHandler() {
	alert("System error occured!");
}

/**
 * Initialize controlls
 */
function initialize() {
	document.getElementById("upload-total-files").className = "plural";
	document.getElementById("upload-total-files").style.display = "";
	document.getElementById("uploadr-bg").className = "uploadr-bg";
	document.getElementById("upload-table").className = "upload";
	document.getElementById("upload-container").className = "upload-container free firefox";
	document.title = "Umpirsky Uploader Demo";
}

/**
 * Remove all files from list
 */
function clearFileList() {
	document.getElementById("upload-files-list").innerHTML = "";
}

/**
 * Remove one file from list
 */
function removeFile(id) {
	// Remove file from dom
	document.getElementById("upload-files-list").removeChild(document.getElementById(id));
	// remove file from uploader
	umpirsky.removeFile(id);
}

/**
 * Updates file list
 */
function updateFileList() {
	// Clear file list
	clearFileList();

	// Create <li> template (file entry)
	var template = document.createElement("li");
	template.setAttribute("class", "default");
	var nameDiv = document.createElement("div");
	nameDiv.setAttribute("class", "name");
	var sizeDiv = document.createElement("div");
	sizeDiv.setAttribute("class", "size");
	var selectDiv = document.createElement("div");
	selectDiv.setAttribute("class", "select");
	var removeLink = document.createElement("a");
	removeLink.setAttribute("class", "remove");
	removeLink.setAttribute("onclick", "remove");
	removeLink.setAttribute("href", "javascript: void(0);");
	removeLink.innerHTML = "&nbsp;";
	selectDiv.appendChild(removeLink);
	template.appendChild(nameDiv);
	template.appendChild(sizeDiv);
	template.appendChild(selectDiv);

	// For each file, clone template and fill wit file data
	for(var i in umpirsky.files) {
		// Temporary template
		var tpl = template.cloneNode(true);

		// Add name and size in template
		tpl.childNodes[0].innerHTML = umpirsky.files[i].name;
		tpl.childNodes[1].innerHTML = umpirsky.files[i].size + " KB";
		tpl.childNodes[2].childNodes[0].setAttribute("onclick", "removeFile('" + umpirsky.files[i].id + "'); return false;");
		tpl.setAttribute("id", umpirsky.files[i].id);
		tpl.setAttribute("title", umpirsky.files[i].name + " - " + umpirsky.files[i].date);

		// Add template to list
		document.getElementById("upload-files-list").appendChild(tpl);
	}

	// Update file counter
	updateFileCounter();

	// Update total size
	updateTotalSize();
}

/**
 * Updates file counter
 */
function updateFileCounter() {
	if (0 == umpirsky.files.length){
		document.getElementById("file-counter").innerHTML = "No files";
	} else if (1 == umpirsky.files.length) {
		document.getElementById("file-counter").innerHTML = 1 + " file";
	} else {
		document.getElementById("file-counter").innerHTML = umpirsky.files.length + " files";
	}
}

/**
 * Update files total size
 */
function updateTotalSize() {
	var total = 0;
	for(var i in umpirsky.files) {
		total = total + parseInt(umpirsky.files[i].size);
	}

	if (0 == total) {
		document.getElementById("upload-total-bytes").innerHTML = "";
	} else {
		document.getElementById("upload-total-bytes").innerHTML = "Total: " + total + " KB";
	}
}

/**
* Upload started
*/
function upload() {
	document.getElementById("uploadr-bg").className = "uploadr-bg-progress";
	document.getElementById("upload-table").className = "upload no-remove";
	umpirsky.upload();
}

/**
 * Triggered when files are uploaded
 * @param String message - response message from server
 */
function filesUploaded(message) {
	umpirsky.clearFiles();
	clearFileList();
	updateFileCounter();
	updateTotalSize();
	initialize();
}

/**
 * Triggered when file upload progress is updated
 * @param int percent - upload progress in %
 */
function uploadProgressListener(percent) {
	document.getElementById("upload-container").className = "upload-container free firefox active uploading";
	document.getElementById("uploadr-status-progress").style.width = 4 * percent + "px";
	document.title = "Uploading... " + "(" + percent + "% complete)";
}